﻿using System;
using System.Collections.Generic;
using System.Linq;

using BodaNetCommunications.CommBase.Interfaces;
using BodaNetCommunications.Utilities.ComTypes;
using BodaNetCommunications.Utilities.Locks;

namespace BodaNetCommunications.McComs
{
    [McPlc(McPLCType.McPlc)]
    //[McPlc(McPLCType.Mitsubishi_Fx3U)]
    internal class McAddressTransfer : IAddressTransfer
    {
        static Dictionary<string, (McAddressArea, string)> _dicts = new Dictionary<string, (McAddressArea, string)>();
        private static object _lock = new object();

        public (McAddressArea, string) TransferAddress(string address)
        {
            if (_dicts.Keys.Contains(address)) return _dicts[address];

            var areaType = typeof(McAddressArea);
            if (false == areaType.IsEnum) throw new Exception($"未获取到{nameof(McPLCType.McPlc)}类型Plc的地址枚举类型");
            // 获取两个字符长度的枚举值名称
            string[] twoLettersEnumNames = Enum.GetNames(areaType).Where(m => m.Length == 2).ToArray();

            string area = address.Substring(0, 2).ToUpperInvariant();
            if (!twoLettersEnumNames.Contains(area))
            {
                area = address.Substring(0, 1).ToUpperInvariant();
            }
            // 软元件的起始地址
            string startAddress = address.Substring(area.Length);

            // 区域代码转枚举
            if (Enum.TryParse<McAddressArea>(area, out var mcAddressArea))
            {
                lock (_lock)
                {
                    if (!_dicts.Keys.Contains(address))
                        _dicts.Add(address, (mcAddressArea, startAddress));
                }

                return (mcAddressArea, startAddress);
            }
            throw new Exception($"McPlc的地址[{address}]解析失败，传入的地址格式不正确");
        }
    }
}